/*
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 */

function SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, cbSearch)
{
	try
	{
		var row = new Object();
		var bgPage = chrome.extension.getBackgroundPage();
		EditViewUI_GetValues(sActionsPanel, sEDIT_NAME, true, row);
		//alert(dumpObj(row, 'SearchViewUI_SearchForm row'));
		var cmd = new Object();
		cmd.CommandText = '';
		if ( row != null )
		{
			for ( var sField in row )
			{
				//alert(sField + ' = ' + row[sField]);
				var oValue = row[sField];
				if ( sField.indexOf(' ') > 0 )
				{
					// 12/05/2011 Paul.  If value is empty, then ignore to prevent search of (0 = 1). 
					if ( !Sql.IsEmptyString(oValue) )
					{
						//alert('multiple fields ' + sField)
						SearchBuilder.Init(oValue);
						var arrFields = sField.split(' ');
						if ( cmd.CommandText.length > 0 )
							cmd.CommandText += ' and ';
						cmd.CommandText += '(0 = 1';
						for ( var n in arrFields )
						{
							if ( typeof(oValue) == 'string' )
								cmd.CommandText += SearchBuilder.BuildQuery(' or ', arrFields[n]);
							else
								Sql.AppendParameter(cmd, arrFields[n], oValue, true);
						}
						cmd.CommandText += ')';
						//alert(cmd.CommandText);
					}
				}
				else
				{
					if ( typeof(oValue) == 'string' )
					{
						if ( cmd.CommandText.length == 0 )
							cmd.CommandText += SearchBuilder.BuildQuery('', sField, oValue);
						else
							cmd.CommandText += SearchBuilder.BuildQuery(' and ', sField, oValue);
					}
					else if ( typeof(oValue) == 'boolean' )
					{
						if ( sField == 'UNASSIGNED_ONLY' )
						{
							Sql.AppendParameter(cmd, 'ASSIGNED_USER_ID', null);
						}
						else if ( sField == 'CURRENT_USER_ONLY' )
						{
							Sql.AppendParameter(cmd, 'ASSIGNED_USER_ID', Security.USER_ID());
						}
						else
						{
							Sql.AppendParameter(cmd, sField, oValue);
						}
					}
					else
					{
						Sql.AppendParameter(cmd, sField, oValue);
					}

				}
			}
		}
		//alert(cmd.CommandText);
		if ( cbSearch !== undefined && cbSearch != null )
			cbSearch(sLayoutPanel, sActionsPanel, cmd.CommandText);
		else
			SplendidError.SystemError('SearchViewUI_SearchForm: cbSearch is not defined');
	}
	catch(e)
	{
		SplendidError.SystemAlert(e, 'SearchViewUI_SearchForm');
	}
}

function SearchViewUI_ClearForm(sLayoutPanel, sActionsPanel, sEDIT_NAME)
{
	try
	{
		EditViewUI_ClearValues(sActionsPanel, sEDIT_NAME);
	}
	catch(e)
	{
		SplendidError.SystemAlert(e, 'SearchViewUI_ClearForm');
	}
}

function SearchViewUI_Clear(sLayoutPanel, sActionsPanel, sMODULE_NAME, sEDIT_NAME, bEnableCaching, cbSearch, callback)
{
	try
	{
		var divMainLayoutPanel = document.getElementById(sActionsPanel);
		//alert('SearchViewUI_Clear(' + sActionsPanel + ')' + divMainLayoutPanel);
		
		var ctlSearchView_tblSearch = document.getElementById(sActionsPanel + '_ctlSearchView_tblSearch');
		if ( ctlSearchView_tblSearch == null )
		{
			if ( divMainLayoutPanel != null && divMainLayoutPanel.childNodes != null )
			{
				while ( divMainLayoutPanel.childNodes.length > 0 )
				{
					divMainLayoutPanel.removeChild(divMainLayoutPanel.firstChild);
				}
			}
			// <table class="tabSearchForm" cellspacing="1" cellpadding="0" border="0" style="width:100%;">
			// <table id="ctlListView_ctlSearchView_tblSearch" class="tabSearchView">
			var ctlSearchView = document.createElement('table');
			ctlSearchView.id        = sActionsPanel + '_ctlSearchView';
			ctlSearchView.cellSpacing = 1;
			ctlSearchView.cellPadding = 0;
			ctlSearchView.border      = 0;
			ctlSearchView.width       = '100%';
			ctlSearchView.className   = 'tabSearchForm';
			var a = document.createElement('a');
			if ( divMainLayoutPanel != null )
			{
				if ( divMainLayoutPanel.childNodes != null && divMainLayoutPanel.childNodes.length > 0 )
					divMainLayoutPanel.insertBefore(ctlSearchView, divMainLayoutPanel.firstChild);
				else
					divMainLayoutPanel.appendChild(ctlSearchView);
			}
			else
			{
				alert('SearchViewUI_Clear: ' + sActionsPanel + ' does not exist');
			}
			
			var tSearchView = document.createElement('tbody');
			ctlSearchView.appendChild(tSearchView);
			var tr = document.createElement('tr');
			tSearchView.appendChild(tr);
			var td = document.createElement('td');
			tr.appendChild(td);
			
			ctlSearchView_tblSearch = document.createElement('table');
			ctlSearchView_tblSearch.id        = sActionsPanel + '_ctlSearchView_tblSearch';
			ctlSearchView_tblSearch.className = 'tabSearchView';
			td.appendChild(ctlSearchView_tblSearch);
			
			var tblSearchButtons = document.createElement('table');
			tblSearchButtons.id               = sActionsPanel + '_ctlSearchView_tblSearchButtons';
			tblSearchButtons.cellSpacing      = 0;
			tblSearchButtons.cellPadding      = 0;
			tblSearchButtons.border           = 0;
			tblSearchButtons.width            = '100%';
			tblSearchButtons.style.paddingTop = '4px';
			td.appendChild(tblSearchButtons);
			
			var tSearchButtons = document.createElement('tbody');
			tblSearchButtons.appendChild(tSearchButtons);
			tr = document.createElement('tr');
			tSearchButtons.appendChild(tr);
			td = document.createElement('td');
			tr.appendChild(td);
			
			// <input type="submit" name="ctl00$cntBody$ctlListView$ctlSearchView$btnSearch" value="Search" 
			// onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$cntBody$ctlListView$ctlSearchView$btnSearch&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" 
			// id="ctl00_cntBody_ctlListView_ctlSearchView_btnSearch" accesskey="Q" title="Search" class="button">
			
			var btnSearch = document.createElement('input');
			btnSearch.type      = 'submit';
			btnSearch.id        = sActionsPanel + '_ctlSearchView_btnSearch';
			btnSearch.value     = L10n.Term('.LBL_SEARCH_BUTTON_LABEL');
			btnSearch.title     = L10n.Term('.LBL_SEARCH_BUTTON_LABEL');
			btnSearch.className = 'button';
			btnSearch.style.marginRight = '3px';
			btnSearch.onclick   = function()
			{
				SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, cbSearch);
			}
			td.appendChild(btnSearch);
			
			var btnClear = document.createElement('input');
			btnClear.type      = 'submit';
			btnClear.id        = sActionsPanel + '_ctlSearchView_btnClear';
			btnClear.value     = L10n.Term('.LBL_CLEAR_BUTTON_LABEL');
			btnClear.title     = L10n.Term('.LBL_CLEAR_BUTTON_LABEL');
			btnClear.className = 'button';
			btnClear.style.marginRight = '3px';
			btnClear.onclick   = function()
			{
				SearchViewUI_ClearForm(sLayoutPanel, sActionsPanel, sEDIT_NAME);
				SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, cbSearch);
			}
			td.appendChild(btnClear);
			
			if ( bEnableCaching )
			{
				var bgPage = chrome.extension.getBackgroundPage();
				var btnCacheSelected = document.createElement('input');
				btnCacheSelected.type      = 'submit';
				btnCacheSelected.id        = sActionsPanel + '_ctlSearchView_btnCacheSelected';
				btnCacheSelected.value     = L10n.Term('.LBL_CACHE_SELECTED');
				btnCacheSelected.title     = L10n.Term('.LBL_CACHE_SELECTED');
				btnCacheSelected.className = 'button';
				btnCacheSelected.style.marginRight = '3px';
				btnCacheSelected.style.display     = (bgPage.GetEnableOffline() && !bgPage.GetIsOffline()) ? 'inline' : 'none';
				btnCacheSelected.onclick   = function()
				{
					SearchViewUI_CacheSelected('chkMain', sMODULE_NAME, callback);
				};
				td.appendChild(btnCacheSelected);
			}
			
			//var txt = document.createTextNode(sActionsPanel);
			//td.appendChild(txt);
		}
		else
		{
			var btnSearch = document.getElementById(sActionsPanel + '_ctlSearchView_btnSearch');
			btnSearch.onclick   = function()
			{
				SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, cbSearch);
			}
			var btnClear = document.getElementById(sActionsPanel + '_ctlSearchView_btnClear');
			btnClear.onclick   = function()
			{
				SearchViewUI_ClearForm(sLayoutPanel, sActionsPanel, sEDIT_NAME);
				SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, cbSearch);
			}
			var btnCacheSelected = document.getElementById(sActionsPanel + '_ctlSearchView_btnCacheSelected');
			if ( btnCacheSelected != null )
			{
				var bgPage = chrome.extension.getBackgroundPage();
				btnCacheSelected.style.display = (bgPage.GetEnableOffline() && !bgPage.GetIsOffline()) ? 'inline' : 'none';
				btnCacheSelected.onclick = function()
				{
					SearchViewUI_CacheSelected('chkMain', sMODULE_NAME, callback);
				};
			}

			if ( ctlSearchView_tblSearch != null && ctlSearchView_tblSearch.childNodes != null )
			{
				while ( ctlSearchView_tblSearch.childNodes.length > 0 )
				{
					ctlSearchView_tblSearch.removeChild(ctlSearchView_tblSearch.firstChild);
				}
			}
			if ( ctlSearchView_tblSearch == null )
			{
				alert('SearchViewUI_Clear: ' + sActionsPanel + '_ctlSearchView_tblSearch' + ' does not exist');
				return;
			}
		}
	}
	catch(e)
	{
		SplendidError.SystemAlert(e, 'SearchViewUI_Clear');
	}
}

function SearchViewUI_CacheSelected(sFieldID, sMODULE_NAME, callback)
{
	try
	{
		var nCacheItemCount = 0;
		var bgPage = chrome.extension.getBackgroundPage();
		
		var fld = document.getElementsByName(sFieldID);
		for (var i = 0; i < fld.length; i++)
		{
			if ( fld[i].type == 'checkbox' )
			{
				if ( fld[i].checked )
				{
					nCacheItemCount++;
					var sID = fld[i].value;
					// 10/11/2011 Paul.  Remove the item from the selected array. 
					if ( arrSELECTED[sID] != null )
					{
						delete arrSELECTED[sID];
					}
					bgPage.DetailView_LoadItem(sMODULE_NAME, sID, function(status, message)
					{
						if ( status == 1 )
						{
							var row = message;
							var chkMain = document.getElementById('chkMain_' + Sql.ToString(row['ID']).replace('-', '_'));
							if ( chkMain != null && chkMain.type == 'checkbox' )
								chkMain.checked = false;
							
							callback(2, 'Loaded ' + sMODULE_NAME + ': ' + row['NAME']);
						}
						nCacheItemCount--;
						if ( nCacheItemCount == 0 )
						{
							callback(2, '');
							var chkMainCheckAll = document.getElementById('chkMainCheckAll');
							if ( chkMainCheckAll != null && chkMainCheckAll.type == 'checkbox' )
								chkMainCheckAll.checked = false;
						}
					});
				}
			}
		}
	}
	catch(e)
	{
		SplendidError.SystemMessage(SplendidError.FormatError(e, 'SearchViewUI_CacheSelected'));
	}
}

function SearchViewUI_Load(sLayoutPanel, sActionsPanel, sMODULE_NAME, sEDIT_NAME, row, bEnableCaching, cbSearch, callback)
{
	try
	{
		var bgPage = chrome.extension.getBackgroundPage();
		bgPage.EditView_LoadLayout(sEDIT_NAME, function(status, message)
		{
			if ( status == 1 )
			{
				// 10/03/2011 Paul.  EditView_LoadLayout returns the layout. 
				var layout = message;
				SearchViewUI_Clear(sLayoutPanel, sActionsPanel, sMODULE_NAME, sEDIT_NAME, bEnableCaching, cbSearch, callback);
				//var layout  = bgPage.SplendidCache.EditViewFields(sEDIT_NAME);
				var tblMain = document.getElementById(sActionsPanel + '_ctlSearchView_tblSearch');
				EditViewUI_LoadView(sActionsPanel, tblMain, layout, row, sActionsPanel + '_ctlSearchView_btnSearch');
				
				callback(1, null);
			}
			else
			{
				callback(status, message);
			}
		});
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'SearchViewUI_Load'));
	}
}

